<template>
  <div class="cart">
    <Header><span slot="back" @click="goDetail">返回详情</span></Header>
    <ul class="cartList" v-if="cartList">
      <li v-for="data in cartList" :key="data._id">
        <input type="checkbox" v-model="data.checked" />
        <img :src="data.product.coverImg" alt="" width="80px" height="80px" />
        <div class="info">
          <h3 class="name">{{ data.product.name }}</h3>
          <span class="price">￥{{ data.product.price }}</span>
          <span @click="data.quantity > 1 && updateNum(data.product._id, -1)"
            >-</span
          >
          <span>{{ data.quantity }}</span>
          <span @click="updateNum(data.product._id, 1)">+</span>
          <van-button
            type="danger"
            size="mini"
            v-if="data.checked"
            @click="del(data._id)"
            >删除</van-button
          >
          <!-- <span v-if="data.checked" @click="del(data._id)" class="del"
						>删除</span
					> -->
        </div>
      </li>
    </ul>
    <div v-else>你太穷了吗宝</div>
    <van-submit-bar :price="alltotal" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="checked">全选</van-checkbox>
      <van-button
        type="danger"
        size="mini"
        v-if="selectList.length > 1"
        @click="delMany()"
        >删除</van-button
      >
    </van-submit-bar>
  </div>
</template>

<script>
import Header from "@/components/header";
import {
  reqCartList,
  reqAddCart,
  reqDelCartList,
  reqDelMany,
} from "@/api/product";
import { reqCreateOrder } from "@/api/order";
import { Notify } from "vant";
export default {
  data() {
    return {
      cartList: [],
    };
  },
  computed: {
    // 选中的商品属性
    selectList() {
      // 定义一个空的数组接收选中的商品。
      let selectArr = [];
      // 判断商品数组中是否有checked，有就是被选中了，将被选中的push到空数组中
      this.cartList.filter((item) => {
        if (item.checked) {
          selectArr.push({
            quantity: item.quantity,
            product: item._id,
            price: item.product.price,
          });
        }
      });
      // 最后必须return出去
      return selectArr;
    },
    // 全选商品的控制
    checked: {
      // 根据全选按钮的状态改变
      set(flag) {
        // 使用set方法将全选商品的状态给商品列表的每个按钮一致
        this.cartList.map((item) => this.$set(item, "checked", flag));
      },
      // 改变就会调用
      get() {
        // 如果没有商品的时候，就返回false
        if (this.cartList.length == 0) {
          return false;
        } else {
          // 判断商品是否全部选中，来返回true或者false。通过判断选中的长度，
          // 和商品的长度是否一样
          return (
            this.cartList.length ==
            this.cartList.filter((item) => item.checked).length
          );
        }
      },
    },
    // 总计
    alltotal() {
      return this.cartList
        .filter((item) => {
          return item.checked;
        })
        .reduce((pre, cur) => {
          return (pre += cur.quantity * cur.product.price * 100);
        }, 0);
    },
  },
  watch: {},

  methods: {
    // 点击 返回详情
    goDetail() {
      this.$router.go(-1);
    },
    // 获取购物车数据，调用接口。
    async getCartList() {
      const res = await reqCartList();
      console.log(res);
      // 获取购物车数组列表
      this.cartList = res;
    },
    //更改商品数量,调用加入购物车接口
    async updateNum(id, num) {
      let data = {
        product: id,
        quantity: num,
      };
      const res = await reqAddCart(data);
      // 调用完接口遍历数组,找出一样的id,给那个id商品加num
      this.cartList.forEach((item) => {
        if (item.product._id == id) {
          item.quantity += num;
        }
      });
    },

    //通过id删除商品
    async del(id) {
      const res = await reqDelCartList(id);
      console.log(res);
      this.cartList.forEach((item, index) => {
        if (item._id == id) {
          this.cartList.splice(index, 1);
        }
      });
    },

    // 删除多个购物车商品
    async delMany() {
      let ids = [];
      // 遍历选中的商品,将id放进ids中
      this.selectList.forEach((item) => {
        ids.push(item.product);
      });
      console.log(ids);
      const res = await reqDelMany({ ids });
      // console.log(res);
      this.getCartList();
    },

    //提交订单
    async onSubmit() {
      // 点击提交的时候要先判断是否有收货人地址
      const receiver = this.$store.state.address.receiver;
      const regions = this.$store.state.address.regions;
      const address = this.$store.state.address.address;
      if (receiver && regions && address) {
        // 有值调接口
        // console.log("我有值了");
        // 调用订单接口,获取传递的参数。计算属性的selectList
        const orderDetails = this.selectList;
        const data = {
          receiver,
          regions,
          address,
          orderDetails,
        };
        // 调用生成订单接口
        const res = await reqCreateOrder(data);
        console.log(res);
        if (res.code == "success") {
          //跳转订单页面
          Notify({
            message: "生成订单成功",
            duration: 1000,
          });
          this.$router.push("/order");
        }
      } else {
        // 没有值跳到address页面
        this.$router.push("/address");
      }
    },
  },
  created() {
    // 调用获取购物车商品列表方法
    this.getCartList();
  },
  mounted() {},
  components: {
    Header,
  },
};
</script>
<style scoped>
.cartList li {
  display: flex;
  align-items: center;
  margin: 5px;
  background-color: #eee;
  height: 100px;
}
.info {
  width: 100%;
  margin-left: 10px;
}
.cartList li .name {
  width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-bottom: 20px;
}
.info span {
  display: inline-block;
  width: 20px;
  height: 20px;
  /* background-color: aqua; */
  border: 1px solid black;
  text-align: center;
  margin-left: 10px;
  line-height: 20px;
  border-radius: 50%;
}
.info span.price {
  width: 70px;
  height: 20px;

  margin-right: 20px;
  border: 0;
}
.van-submit-bar {
  margin-bottom: 50px;
}
.info span.van-button__text {
  width: 50px;
  border: 0;
}
.van-button {
  top: -5px;
  margin-left: 10px;
}
</style>
